package com.example.mobifin_busticket.controller.networkmanager;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.MD5Generator;
import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.views.dialogs.RegistrationDialog;
import com.example.mobifin_busticket.views.dialogs.Registration_Process;

public class Async_getActivationKey extends AsyncTask<Void, Void, JSONObject> {

	private Handler handler = new Handler();
	MD5Generator generator = new MD5Generator();
	Context mContext;
	String kycId;
	String phoneNumber;
	String EmailAddress;
	String EncryptedLoginID;

	Dialog dialog;

	public Async_getActivationKey(Context ctx, String kycId,
			String phoneNumber, String EmailAddress,
			RegistrationDialog registerDialog) {
		this.mContext = ctx;

		this.kycId = kycId;
		this.phoneNumber = phoneNumber;
		this.EmailAddress = EmailAddress;

		this.dialog = registerDialog;
	}

	@Override
	protected void onPreExecute() {
		MyApplication.showProgressDialog(mContext, "Please Wait..");
	}

	@Override
	protected JSONObject doInBackground(Void... params) {
		System.out.println("`````````In GetActivation Thread...");

		try {

			String terminalinfo;
			// DeviceUUID deviceUUID=new DeviceUUID(mContext);
			WindowManager wm = (WindowManager) mContext
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			terminalinfo = "Android" + "," + android.os.Build.MODEL + ","
					+ android.os.Build.ID + "," + display.getWidth() + "x"
					+ display.getHeight() + "," + android.os.Build.MANUFACTURER
					+ "," + android.os.Build.BOARD + ","
					+ android.os.Build.DISPLAY + ","
					+ android.os.Build.FINGERPRINT;
			Log.i("Test", "KYCInfo:" + kycId + " phone:" + phoneNumber
					+ " email:" + EmailAddress);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7);
			nameValuePair.add(new BasicNameValuePair("AccessType",
					AppData.AccessType));
			nameValuePair.add(new BasicNameValuePair("TerminalType",
					AppData.TerminalType));
			// nameValuePair.add(new BasicNameValuePair("TerminalType", "MOB"));
			nameValuePair.add(new BasicNameValuePair("TerminalInfo",
					terminalinfo));
			//kyc,phone and email apne server ne post kariye che
			nameValuePair.add(new BasicNameValuePair("KYCInfo", kycId));
			nameValuePair.add(new BasicNameValuePair("Phone", phoneNumber));
			nameValuePair.add(new BasicNameValuePair("EmailAddress",
					EmailAddress));
			nameValuePair.add(new BasicNameValuePair("function",
					"GetTerminalNumber"));
			// kyc phone and email server ne mokalvanu...etle server terminal
			// number generate karse..
			String response = createHttpConnNew(mContext, nameValuePair,
					AppData.terminalNumberHostURL);
			System.out.println("Result:" + response);

			if (response == null) {
				handler.post(new Runnable() {
					public void run() {
						MyApplication.dismissProgressDialog();
						Toast.makeText(mContext, "Server nt replied",
								Toast.LENGTH_SHORT).show();
					}
				});
				return null;
			} else {
				final JSONObject jsonObject = new JSONObject(response);

				return jsonObject;
			}
		} catch (final Exception e) {
			handler.post(new Runnable() {
				public void run() {
					MyApplication.dismissProgressDialog();
					Toast.makeText(mContext,
							e.toString() + "\n" + e.getMessage(),
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			});
			return null;
		}
	}

	public String createHttpConnNew(Context c,
			List<NameValuePair> nameValuePair, String URL) {
		String result = null;
		HttpClient httpclient = null;
		HttpParams params;
		String clientInfo;

		try {
			params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, 15000);
			HttpConnectionParams.setSoTimeout(params, 18000);
			System.out.println("url-->is" + URL);
			httpclient = new DefaultHttpClient();
			HttpPost request = new HttpPost(URL);

			WindowManager wm = (WindowManager) c
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			clientInfo = "Android" + "," + "," + android.os.Build.MODEL + ","
					+ android.os.Build.ID + "," + display.getWidth() + "x"
					+ display.getHeight() + "," + android.os.Build.MANUFACTURER
					+ "," + android.os.Build.BOARD + ","
					+ android.os.Build.DISPLAY + ","
					+ android.os.Build.FINGERPRINT;

			request.addHeader("Client", clientInfo);
			request.addHeader("Application_Version_Tracker",
					AppData.app_tracking_pattern);

			System.out.println("-------Header Parameter-------");
			System.out.println("Client:" + clientInfo);
			System.out.println("Application_Version_Tracker: "
					+ AppData.app_tracking_pattern);
			// request.addHeader("deviceId", deviceId);
			// request.addHeader("Content-Type","application/json");

			try {
				request.setEntity(new UrlEncodedFormEntity(nameValuePair));
			} catch (UnsupportedEncodingException e) {
				// writing error to Log
				e.printStackTrace();
			}

			ResponseHandler<String> handler = new BasicResponseHandler();
			result = httpclient.execute(request, handler);

			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	@Override
	protected void onPostExecute(JSONObject jsonObject) {
		try {
			if (jsonObject != null) {
				//ahiya response chk karavyo.
				String responseCode = jsonObject.getString("ResponseCode");
				final String responseDesc = jsonObject
						.getString("ResponseDescription");
				String currency, PublicKey;

				if (responseCode.equals("000"))/*
												 * &&
												 * responseDesc.equals("Successful"
												 * )
												 */
				{
					MyApplication.dismissProgressDialog();
					dialog.dismiss();
					
					//TerminalKeyActivity register = new TerminalKeyActivity(
						//	mContext);
					
//ahiya resposen mathi treminalrequestID extract kari ne aagal na form ma mokalishu
					if (!jsonObject.getString("TerminalRequestID").equals(null)
							&& jsonObject.getString("TerminalRequestID")
									.length() > 0) {
						// Toast.makeText(mContext, "Terminal Req id : " +
						// jsonObject.getString("TerminalRequestID"),
						// Toast.LENGTH_SHORT).show();
						
						//terminalrequestID add karyu ..joyu?ha.ok
						Registration_Process registerProcess=new Registration_Process(mContext, kycId, phoneNumber, EmailAddress,jsonObject
								.getString("TerminalRequestID"));
						//TerminalKeyActivity register = new TerminalKeyActivity(
							//	mContext);
						registerProcess.show();
						
						
					}
				} else {
					MyApplication.dismissProgressDialog();
					Toast.makeText(mContext, responseDesc, Toast.LENGTH_SHORT)
							.show();
				}
			}
		} catch (Exception e) {
			MyApplication.dismissProgressDialog();
			Toast.makeText(
					mContext,
					e.toString() + "\n" + e.getMessage()
							+ "\n In GetLogin Thread..", Toast.LENGTH_SHORT)
					.show();
			e.printStackTrace();
		}
	}
}